import MethodChannel from '@/api/MethodChannel.js'
import {commonAjaxGet, commonAjax} from '@/vendors/request/index.js'
import store from '@/store/index.js';

export function clearUrlParam() {
    location.href = location.href.slice(0, location.href.indexOf('?') > 0 ? location.href.indexOf('?') : location.href.length)
}

export function isUndefined(value) {
    return value === 'undefined'
}

/**
 * 获取语言
 * @returns language
 */
export function getLanguage() {
    let language = localStorage.getItem('trtc-quick-vue2-language') || getUrlParam('lang') || navigator.language || 'zh'
    language = language.replace(/_/, '-').toLowerCase()

    if (language === 'zh-cn' || language === 'zh') {
        language = 'zh'
    } else if (language === 'en' || language === 'en-us' || language === 'en-GB') {
        language = 'en'
    }
    return language
}

/**
 * 当前浏览器是否为移动端浏览器
 */
export const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)

function findRecursion(parent, label, result) {
    for (var i = 0; i < parent.children.length; i++) {
        if (parent.children[i].tagName == label) {
            result.push(parent.children[i])
        }

        findRecursion(parent.children[i], label, result)
    }
    return result
}

export function findDom(parent, label) {
    return findRecursion(parent, label, [])
}

export function getUrlParam(url, name) {
    var reg = /([^&^\?^\/^#^;]*?)=(.*?)(?=$|&|#|\?|\/)/g
    var result
    while ((result = reg.exec(url))) {
        if (result[1] == name) {
            return decodeURIComponent(result[2])
        }
    }
    return ''
}

export function toast(title, duration = 3000, mask = false, icon = 'none') {
    if (Boolean(title) === false) {
        return
    }
    uni.showToast({
        title,
        duration,
        mask,
        icon,
    })
}

export function logout() {
    uni.removeStorageSync('loginInfo');
    uni.reLaunch({
        url: '/pages/login/index'
    });
}

export function getLoginInfo() {
    let {yhdm,pwd,jgid,tenantId,jsonRootBean} = uni.getStorageSync('loginInfo');
    console.log('utils;getLoginInfo;yhdm', yhdm + ";pwd=" + pwd + ";jgid=" + jgid);
    if (yhdm && pwd && jgid) {
        let params = {
            yhdm,
            pwd,
            jgid,
            tenantId,
            jsonRootBean
        }
        // 这并不是真正的登录，当做获取用户信息的接口
        commonAjax("mobile/user/login", params).then((result) => {
            if (result.res.ReType == 0) {
                store.commit("setLoginUser", result.res?.Data?.loginUser);
                store.commit("setArea", result.res?.Data?.Areas);
            }else {
                logout();
            }
        });
    }
}
